﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OutbreakForecast.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace OutbreakForecast
{
    public class DataHelper
    {
        private string fileGlobal = Path.Combine(Application.StartupPath, "nCoV2019_Predict_data_Global.json");
        private string fileChina = Path.Combine(Application.StartupPath, "nCoV2019_Predict_data_China.json");

        public DataHelper()
        {
            try
            {
                new Thread(() =>
                {
                    var dataString = new WebClient { Encoding = Encoding.UTF8 }.DownloadString("https://coronavirus-tracker-api.herokuapp.com/all");
                    Write(fileGlobal, dataString);
                }).Start();
            }
            catch (Exception ex)
            {
                Debug.Print("信息异常：" + ex.ToString());
            }
        }

        public dynamic GetChinaNow()
        {
            var dataString = new WebClient { Encoding = Encoding.UTF8 }.DownloadString("https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5");
            var DataJson = JsonConvert.DeserializeObject<RootObject>(dataString).data;
            dynamic json = JValue.Parse(DataJson);
            var od = new { updateTime = json.lastUpdateTime.ToString(), confirm = json.chinaTotal.confirm.ToString(), heal = json.chinaTotal.heal.ToString(), dead = json.chinaTotal.dead.ToString() };
            return $"更新时间UpdateTime：{od.updateTime}，确诊Confirm：{od.confirm}，治愈Heal：{od.heal}，死亡Dead：{od.dead}";
        }

        public dynamic GetGlobalNow()
        {
            var json = JsonConvert.DeserializeObject<dynamic>(File.ReadAllText(fileGlobal));
            var od = new { updateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), confirm = json.latest.confirmed.ToString(), heal = json.latest.recovered.ToString(), dead = json.latest.deaths.ToString() };
            return $"更新时间UpdateTime：{od.updateTime}，确诊Confirm：{od.confirm}，治愈Heal：{od.heal}，死亡Dead：{od.dead}";
        }

        public DataRaw[] GetChina()
        {
            var dataString = new WebClient { Encoding = Encoding.UTF8 }.DownloadString("https://view.inews.qq.com/g2/getOnsInfo?name=wuwei_ww_cn_day_counts");
            Write(fileChina, dataString);
            var dataJson = JsonConvert.DeserializeObject<RootObject>(dataString).data;
            return JsonConvert.DeserializeObject<DataRaw[]>(dataJson);
        }

        public DataRaw[] GetGlobal()
        {
            Dictionary<string, int> Get(dynamic dataType)
            {
                var dic = new Dictionary<string, int>();
                foreach (var i in dataType)
                {
                    var v = i.history;
                    foreach (var item in v)
                    {
                        var day = item.Name;
                        var val = int.Parse(item.Value.Value.ToString());
                        if (dic.ContainsKey(day))
                        {
                            dic[day] += val;
                        }
                        else
                        {
                            dic.Add(day, val);
                        }
                    }
                }
                return dic;
            }

            var json = JsonConvert.DeserializeObject<dynamic>(File.ReadAllText(fileGlobal));
            var confirmed = Get(json.confirmed.locations);
            var recovered = Get(json.recovered.locations);
            var deaths = Get(json.deaths.locations);

            var da = new List<DataRaw>();
            foreach (var item in confirmed)
            {
                try
                {
                    da.Add(new DataRaw()
                    {
                        date = item.Key + "20",
                        confirm = item.Value,
                        heal = recovered[item.Key],
                        dead = deaths[item.Key]
                    });
                }
                catch (Exception ex)
                {
                    Debug.Print("信息异常：" + ex.ToString());
                }
            }
            return da.ToArray();
        }

        private void Write(string file, string dataString)
        {
            try
            {
                if (File.Exists(file) && !string.IsNullOrWhiteSpace(dataString))
                    File.Delete(file);
                File.WriteAllText(file, dataString);
            }
            catch (Exception ex)
            {
                Debug.Print("信息异常：" + ex.ToString());
            }
        }
    }
}